<template>
  <div class="discountSet-box">
    <div class='container'>
      <div class="setContainer">
        <div class="aside">
          <el-header>
            <span>参与折上折门票</span>
            <span class="el-icon-edit" v-on:click="dialogVisible1=true,showCheck()"></span>
          </el-header>
          <ul class="dataUl">
            <div v-if="setTicketDiscout.length<1" class="noData">暂无参与折上折门票,请设置</div>
            <li class="dataList" :key="item.ticketTypeId" v-for="item in setTicketDiscout">{{item.tTypeName}} </li>
          </ul>
        </div>
        <div class="aside">
          <el-header>
            <span>折扣设置</span>
            <span class="el-icon-edit" v-on:click="openSetDiscount()"></span>
          </el-header>
          <ul class="dataUl">
            <li class="dataList" :key='i' v-for="(item,i) in showSetDiscount">
              <span>订单满{{item.discountNum}}张门票，{{item.discount}}折
              </span>
              <i class="el-icon-delete" v-on:click="deleteDiscount(item.id)"></i>
            </li>
          </ul>
        </div>
      </div>
      <div class="btn">
        <el-button icon="el-icon-check" size="small" @click="setTicket">保存设置</el-button>
      </div>
    </div>

    <!-- 其它设置页面复制过来的 -->
    <div class="other-swapper">
      <div class="menu-box">
        <el-button icon="el-icon-check" size="small" @click="onSubmit">立即创建</el-button>
      </div>
      <el-form :model="form" ref="form" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="开售时间">
              <el-date-picker style="width:100%" v-model="form.startSaleDate" type="datetime" value-format="timestamp" placeholder="请选择开售时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="倒计时开始时间">
              <el-date-picker style="width:100%" v-model="form.countdownDate" type="datetime" value-format="timestamp" placeholder="请选择倒计时开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="限购数量设置">
              <el-input-number style="width:100%" v-model="form.limitNum" :step="1" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="限购邮箱设置">
              <el-input v-model.trim="form.connectEmail" placeholder="请输入限购邮箱设置"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="客服电话">
              <el-input-number style="width:100%" v-model="form.customerServiceTel" :controls="false" :step="1" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="团购票数量设置">
              <el-input-number style="width:100%" v-model="form.groupNum" :step="1" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-dialog title="参与折上折门票" class="setDialog" :visible.sync="dialogVisible1">
      <ul class="dataUl">
        <div v-if="ticketList.length<1" class="noData">暂无可参与折上折的门票</div>
        <li class="discountList" :key="i" v-for="(item,i) in ticketList">
          <span>{{item.tTypeName}}</span>
          <el-checkbox v-model="item.isChecks"></el-checkbox>
        </li>
      </ul>
      <div class="footer">
        <el-button type="primary" v-on:click="sessionTicket()" size="small">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="折扣设置" class="setDialog" :visible.sync="dialogVisible2">
      <ul>
        <li class="setList" :key="i" v-for="(item,i) in argumentTicket">订单满
          <el-input-number :disabled="true" size="mini" v-model="item.discountNum" controls-position="right"></el-input-number> 张,
          <el-input-number :disabled="true" size="mini" v-model="item.discount" controls-position="right"></el-input-number> 折
          <i class="el-icon-delete" v-on:click="deleteSet(i)"></i>
        </li>
        <li class="setList">订单满
          <el-input-number size="mini" v-model="addDiscount.discountNum" controls-position="right" @change="handleChange" :min="1" :max="1000"></el-input-number> 张,
          <el-input-number size="mini" v-model="addDiscount.discount" :precision="2" :step="0.01" controls-position="right" @change="handleChange" :min="0.01" :max="10"></el-input-number> 折
          <i class="el-icon-plus" v-on:click="addSet()"></i>
        </li>
      </ul>
      <div class="footer">
        <el-button type="primary" v-on:click="setTicket()" :disabled="argumentTicket.length==0" size="small">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      checked: false,
      dialogVisible1: false, //参与折上折门票的弹框可见与否
      dialogVisible2: false, //折门设置的弹框可见与否
      form: {},
      ticketList: [], //门票列表
      setTicketDiscout: [], //折上折显示页面
      ticketTypeIds: [], //门票id
      addDiscount: {
        activityId: this.$store.state.activityId,
        corpId: localStorage.getItem("corpId"),
        discountNum: 0,
        discount: null,
        ticketTypeIds: []
      }, //添加折扣
      showSetDiscount: [],
      list: [],
      argumentTicket: [
        // {
        //   activityId: this.$store.state.activityId,
        //   corpId: localStorage.getItem("corpId"),
        //   discountNum: null,
        //   discount: null,
        //   ticketTypeIds: []
        // }
      ] //设置折上折参数
    };
  },
  computed: {
    thisActivityId() {
      return this.$store.state.activityId;
    }
  },
  watch: {
    thisActivityId(a, b) {
      // console.log("修改前为：" + a);
      // console.log("修改后为：" + b);
      this.addDiscount.activityId = a;
      this.getTicketList();
      this.queryById();
      this.getList();
    }
  },
  methods: {
    // 排序
    compare: function(property) {
      return function(a, b) {
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
      };
    },
    // 显示哪些门票已选
    showCheck: function() {
      let length1 = null;
      let length2 = null;
      if (this.ticketList && this.ticketList.length > 0) {
        length1 = this.ticketList.length;
      }
      if (this.setTicketDiscout && this.setTicketDiscout.length > 0) {
        length2 = this.setTicketDiscout.length;
      }
      for (let i = 0; i < length1; i++) {
        for (let j = 0; j < length2; j++) {
          if (
            this.ticketList[i].ticketTypeId ==
            this.setTicketDiscout[j].ticketTypeId
          ) {
            this.ticketList[i].isChecks = true;
          } else {
          }
        }
      }
    },
    //获取已设置的折扣门票
    getList: function() {
      let t = this;
      t.ticketTypeIds = [];
      let parms = {
        activityId: this.$store.state.activityId,
        corpId: localStorage.getItem("corpId")
      };
      this.$http
        .post(
          "/api/isv/tokenMethod/queryTicketTypeListDiscountByActivityId",
          parms
        )
        .then(
          res => {
            if (res.data.success) {
              t.setTicketDiscout = res.data.result;
              if (t.setTicketDiscout) {
                t.setTicketDiscout.map(item => {
                  t.ticketTypeIds.push(item.ticketTypeId);
                });
              }
            } else {
              this.$message({
                message: res.data.errorMsg || "获取已设置门票失败",
                type: "warning"
              });
            }
          },
          error => {
            this.$message.error("服务器出小差了");
          }
        );
    },
    // 获取设置好的折扣数据
    getDiscount: function() {
      // let ticketTypeIds = [];
      // this.setTicketDiscout = [];
      this.argumentTicket = [];
      let parms = {
        activityId: this.$store.state.activityId,
        corpId: localStorage.getItem("corpId")
      };
      this.$http
        .post("/api/isv/tokenMethod/queryTicketTypeDiscountByActivityId", parms)
        .then(
          res => {
            if (res.data.success) {
              this.showSetDiscount = res.data.result;
              if (this.showSetDiscount.length == 0) {
                this.ticketList.map(item => {
                  item.isChecks = false;
                });
                this.setTicketDiscout = [];
              }
              if (res.data.result.length > 0) {
                res.data.result.map(item => {
                  this.argumentTicket.push({
                    activityId: item.activityId,
                    corpId: item.corpId,
                    discountNum: item.discountNum,
                    discount: item.discount,
                    ticketTypeIds: item.ticketTypeIds
                  });
                });
              }
              // if (res.data.result.length > 0) {
              //   res.data.result.map(item => {
              //     item.ticketTypeIds = JSON.parse(item.ticketTypeIds);
              //     ticketTypeIds = ticketTypeIds.concat(item.ticketTypeIds);
              //     ticketTypeIds = Array.from(new Set(ticketTypeIds));
              //   });

              //   for (let i = 0; i < ticketTypeIds.length; i++) {
              //     for (let j = 0; j < this.ticketList.length; j++) {
              //       if (ticketTypeIds[i] == this.ticketList[j].ticketTypeId) {
              //         this.setTicketDiscout.push({
              //           tTypeName: this.ticketList[j].tTypeName
              //         });
              //       }
              //     }
              //   }
              //   return this.setTicketDiscout;
              // }
            } else {
              this.$message({
                message: res.data.errorMsg || "获取已设置门票失败",
                type: "warning"
              });
            }
          },
          error => {
            this.$message.error("服务器出小差了");
          }
        );
    },
    // 删除已设置好的折扣数据（数据库）
    deleteDiscount: function(id) {
      let parms = {
        activityId: this.$store.state.activityId,
        id: id
      };
      this.$confirm("您确定是否要进行删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http
          .post("/api/isv/tokenMethod/delTicketTypeDiscount", parms)
          .then(
            res => {
              if (res.data.success) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.getDiscount();
              } else {
                this.$message({
                  message: res.data.errorMsg || "删除失败",
                  type: "warning"
                });
              }
            },
            err => {
              this.$message.error("服务器出小差了");
            }
          );
      });
    },
    // 设置折扣
    setTicket: function() {
      let t = this;
      this.argumentTicket.map(item => {
        item.ticketTypeIds = JSON.stringify(this.ticketTypeIds);
      });
      let arr = this.argumentTicket.sort(this.compare("discountNum"));
      console.log(arr, "00000");
      console.log(this.argumentTicket);
      // this.argumentTicket.map(item=>{
      t.$http
        .post(
          "/api/isv/tokenMethod/addEditTicketTypeDiscount",
          this.argumentTicket
        )
        .then(
          res => {
            if (res.data.success) {
              this.dialogVisible2 = false;
              // this.argumentTicket = [];
              // this.ticketTypeIds = [];
              t.$message({
                message: res.data.result || "设置成功",
                type: "success"
              });
              this.getDiscount();
            } else {
              t.$message({
                message: res.data.errorMsg || "设置失败",
                type: "warning"
              });
            }
          },
          error => {
            t.$message.error("服务器出小差了");
          }
        );

      this.addDiscount = {
        activityId: this.$store.state.activityId,
        corpId: localStorage.getItem("corpId"),
        discountNum: 1,
        discount: null,
        ticketTypeIds: []
      };
      // })
    },
    //  暂存设置的折扣门票
    sessionTicket: function() {
      let num = 0;
      this.setTicketDiscout = [];
      this.ticketTypeIds = [];
      console.log("this.ticketTypeIds");
      this.ticketList.map(item => {
        if (
          item.isChecks == true &&
          !this.ticketTypeIds.includes(item.ticketTypeId)
        ) {
          num++;
          this.setTicketDiscout.push(item);
          this.ticketTypeIds.push(item.ticketTypeId);
        }
      });
      console.log(num, "00000");
      if (num == 0) {
        this.$message({
          message: "请选择要设置折扣的门票",
          type: "warning"
        });
      } else {
        this.dialogVisible1 = false;
      }
    },
    // 重置
    reset: function() {
      this.ticketList.map(item => {
        item.isChecks = false;
      });
      this.ticketTypeIds = [];
    },
    // 获取门票
    getTicketList: function() {
      this.$http
        .post("/api/isv/ticketPurchasePC/queryTicketTypeList", {
          activityId:
            this.$store.state.activityId || localStorage.getItem("activityId"),
          isPay: "pay"
        })
        .then(
          res => {
            if (res.data.success) {
              if (res.data.result.length) {
                res.data.result.map(item => {
                  item.isChecks = false;
                });
              }
              this.ticketList = res.data.result;
              this.getDiscount();
            } else {
              this.$message({
                message: res.data.errorMsg || "数据获取失败",
                type: "warning"
              });
            }
          },
          error => {
            this.$message.error("服务器出小差了");
          }
        );
    },
    openSetDiscount: function() {
      if (this.ticketTypeIds.length < 1) {
        this.$message({
          message: "请先选择票",
          type: "warning"
        });
      } else {
        this.dialogVisible2 = true;
      }
    },
    //添加折扣设置
    addSet: function() {
      if (!this.addDiscount.discountNum || !this.addDiscount.discount) {
        this.$message({
          message: "折扣信息不全",
          type: "warning"
        });
        return;
      }
      this.addDiscount.ticketTypeIds = JSON.stringify(this.ticketTypeIds);
      this.argumentTicket.push(this.addDiscount);
      this.addDiscount = {
        activityId: this.$store.state.activityId,
        corpId: localStorage.getItem("corpId"),
        discountNum: 1,
        discount: null,
        ticketTypeIds: []
      };
    },
    // 删除折扣设置
    deleteSet: function(i) {
      this.argumentTicket.splice(i, 1);
    },
    handleChange: function() {},
    queryById() {
      this.$http
        .post("/api/isv/activity/queryActivityById", {
          activityId: this.$store.state.activityId
        })
        .then(
          res => {
            if (res.data.success) {
              this.form = res.data.result;
            } else {
              this.$message({
                message: res.data.errorMsg || "数据获取失败",
                type: "warning"
              });
            }
          },
          err => {
            this.$message.error("服务器出小差了");
          }
        );
    },
    onSubmit() {
      this.form.endDate = this.form.enddate;
      let regu = /@/;
      let re = new RegExp(regu);
      if (this.form.connectEmail && !re.test(this.form.connectEmail)) {
        this.$message({
          message: "请填写正确邮箱",
          type: "warning"
        });
        return;
      }
      this.$http.post("/api/isv/activity/updateOtherSet", this.form).then(
        res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "创建成功!"
            });
            this.queryById();
          } else {
            this.$message({
              message: res.data.errorMsg || "数据提交失败",
              type: "warning"
            });
          }
        },
        err => {
          this.$message.error("服务器出小差了");
        }
      );
    }
  },
  created() {
    this.getTicketList();
    this.queryById();
    this.getList();
  }
};
</script>
<style scoped>
.discountSet-box {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 6px;
  /* padding: 0 10px; */
}
.container {
  width: 100%;
}
.aside {
  min-height: 200px;
  height: 100%;
  padding-bottom: 10px;
  width: 48% !important;
  background: #fff;
}

.setContainer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.el-header {
  height: 45px !important;
  line-height: 45px !important;
  border-bottom: 1px solid #eee;
  position: relative;
}

.el-icon-edit {
  margin-top: 10px;
  position: absolute;
  right: 20px;
}
.dataUl {
  width: 95%;
  min-height: 200px;
  margin-left: 20px;
  padding-top: 10px;
}
.noData {
  width: 100%;
  height: 30px;
  text-align: center;
  margin-top: 80px;
  color: #e4e4e4;
}
.dataList {
  display: flex;
  justify-content: space-between;
  padding-right: 15px;
  line-height: 30px;
}
/* 参与折上折门票 */
.discountList {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.footer {
  text-align: center;
  margin-top: 20px;
}
/* 折扣设置 */
.setList {
  margin-bottom: 15px;
  list-style: none;
}

.other-swapper {
  margin-top: 15px;
  width: 100%;
  background: #fff;
  border-radius: 6px;
  padding: 26px 26px;
}
.menu-box {
  text-align: right;
  padding-bottom: 20px;
}
.el-icon-plus,
.el-icon-delete {
  cursor: pointer;
}
.btn {
  text-align: center;
  background: #fff;
  margin-top: 10px;
  padding: 10px 0;
}
</style>
